#include "log.h"

const QString     g_logFile=QString("C:\\Users\\Public\\Documents\\DW\\log.txt");
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
void outputMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    static QMutex mutex;
    if(!isFileExist(g_logFile)){
        QFile f(g_logFile);
        f.open(QIODevice::WriteOnly);
        f.close();
    }
    QFile file(g_logFile);
    if(file.size()< MASXSIZELOG)
       file.open(QIODevice::WriteOnly | QIODevice::Append);
    else
       file.open(QIODevice::WriteOnly | QIODevice::Truncate);
    mutex.lock();

    QString text;
    switch(type)
    {
    case QtDebugMsg:
    {
        text = QString("[DEBUG]:");
        QString current_date_time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
        QString current_date = QString("%1").arg(current_date_time);
        QString message = QString("%1 %2 %3").arg(text).arg(current_date).arg(msg);
        QTextStream text_stream(&file);
        text_stream << message << "\r\n";
        break;
    }
    case QtWarningMsg:{
        break;
    }
    case QtCriticalMsg:
    {
        text = QString("[   CRITICAL]:");
        QString context_info = QString("File:%1  Line:%2").arg(QString(context.file)).arg(context.line);///文件名和行号
        QString current_date_time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
        QString current_date = QString("%1").arg(current_date_time);
        QString message = QString("%1 %2 %3  %4").arg(text).arg(current_date).arg(context_info).arg(msg);
        QTextStream text_stream(&file);
        text_stream << message << "\r\n";
        break;
    }
    case QtFatalMsg: {
        text = QString("[   FATAL]:");
        QString context_info = QString("File:%1  Line:%2").arg(QString(context.file)).arg(context.line);///文件名和行号
        QString current_date_time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
        QString current_date = QString("%1").arg(current_date_time);
        QString message = QString("%1 %2 %3  %4").arg(text).arg(current_date).arg(context_info).arg(msg);
        QTextStream text_stream(&file);
        text_stream << message << "\r\n";
        break;
    }
    case QtInfoMsg: {
        text = QString("[   INFO]:");
        QString context_info = QString("File:%1  Line:%2").arg(QString(context.file)).arg(context.line);///文件名和行号
        QString current_date_time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
        QString current_date = QString("%1").arg(current_date_time);
        QString message = QString("%1 %2 %3  %4").arg(text).arg(current_date).arg(context_info).arg(msg);
        QTextStream text_stream(&file);
        text_stream << message << "\r\n";
        break;
    }
    }
    file.flush();
    file.close();
    mutex.unlock();
}
#endif
